﻿using System.Text.RegularExpressions;
using Admin.NET.Core;
using Vboot.Core.Module.Ass;

namespace Vboot.Core.Module.Gen;

[ApiDescriptionSettings("Gen")]
public class GenAttApi : IDynamicApiController
{
    private SqlSugarRepository<AssFileAtt> _fileRepo;

    private readonly UploadOptions _uploadOptions;
    
    
    private readonly IHttpContextAccessor _httpContextAccessor;


    public GenAttApi(SqlSugarRepository<AssFileAtt> fileRepo,
        IOptions<UploadOptions> uploadOptions,
        IHttpContextAccessor httpContextAccessor)
    {
        _fileRepo = fileRepo;
        _uploadOptions = uploadOptions.Value;
        _httpContextAccessor = httpContextAccessor;
    }

    [NonUnify]
    public async Task<AssFileAtt> PostUp(IFormFile file)
    {
        Console.WriteLine(file);
        var sysFile = await HandleUploadFile(file);
        return sysFile;
    }

    [QueryParameters]
    public IActionResult GetPath(string name, string path)
    {
        // var file = await GetFile(input);
        // var fileName = HttpUtility.UrlEncode(file.FileName, Encoding.GetEncoding("UTF-8"));
        // var filePath = Path.Combine(file.FilePath, input.Id.ToString() + file.Suffix);
        var downloadPath = Path.Combine(App.WebHostEnvironment.WebRootPath, path);
        _httpContextAccessor.HttpContext.Response.Headers.Add("download-filename", name);
        return new FileStreamResult(new FileStream(downloadPath, FileMode.Open), "application/octet-stream")
            {FileDownloadName = name};
    }

    /// <summary>
    /// 上传文件
    /// </summary>
    /// <param name="file">文件</param>
    /// <returns></returns>
    private async Task<AssFileAtt> HandleUploadFile(IFormFile file)
    {
        string path = _uploadOptions.Path;
        var reg = new Regex(@"(\{.+?})");
        var match = reg.Matches(path);
        match.ToList().ForEach(a =>
        {
            var str = DateTime.Now.ToString(a.ToString().Substring(1, a.Length - 2));
            path = path.Replace(a.ToString(), str);
        });

        // if (!_uploadOptions.ContentType.Contains(file.ContentType))
        //     throw Oops.Oh(ErrorCodeEnum.D8001);

        var sizeKb = (long) (file.Length / 1024.0); // 大小KB
        // if (sizeKb > _uploadOptions.MaxSize)
        //     throw Oops.Oh(ErrorCodeEnum.D8002);

        var suffix = Path.GetExtension(file.FileName).ToLower(); // 后缀
        if (suffix.Length > 0)
        {
            suffix = suffix.Substring(1);
        }

        // 先存库获取Id
        var newFile = await _fileRepo.AsInsertable(new AssFileAtt
        {
            id = YitIdHelper.NextId() + "",
            pname = Path.GetFileNameWithoutExtension(file.FileName),
            sname = suffix,
            zsize = sizeKb.ToString(),
            addre = path
        }).ExecuteReturnEntityAsync();

        var finalName = newFile.id + "." + suffix; // 文件最终名称
        var filePath = Path.Combine(App.WebHostEnvironment.WebRootPath, path);
        if (!Directory.Exists(filePath))
            Directory.CreateDirectory(filePath);
        using var stream = File.Create(Path.Combine(filePath, finalName));
        await file.CopyToAsync(stream);
        return newFile;
    }
}